package cn.com.ebidding.controller;

import cn.com.ebidding.business.annotation.BussinessLog;
import cn.com.ebidding.business.entity.File;
import cn.com.ebidding.business.service.BizFileService;
import cn.com.ebidding.business.vo.FileConditionVO;
import cn.com.ebidding.file.ApiClient;
import cn.com.ebidding.file.FtpApiClient;
import cn.com.ebidding.framework.holder.SpringContextHolder;
import cn.com.ebidding.framework.object.ResponseVO;
import cn.com.ebidding.util.ResultUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件管理
 *
 * @author 扫地僧 (saods@ebidding.com.cn)
 * @version 1.0
 * @website https://ksp.ebidding.com.cn
 * @date 2019/2/14 11:37
 * @since 1.0
 */
@RestController
@RequestMapping("/file")
public class RestFileController {
    private static final String UTF_8 = "UTF-8";

    @Autowired
    private BizFileService fileService;
    /** 
    * @Description: 文件管理
    * @Param: [vo] 
    * @return: com.github.pagehelper.PageInfo 
    * @Author: wanfy
    * @Date: 2019/3/11 10:13 AM
    */ 
    @RequiresPermissions("files")
    @PostMapping("/list")
    public PageInfo list(FileConditionVO vo) {
        vo.setPageSize(20);
        return fileService.findPageBreakByCondition(vo);
    }

    /**
     * @Description: 文件管理
     * @Param: [vo]
     * @return: com.github.pagehelper.PageInfo
     * @Author: wanfy
     * @Date: 2019/3/11 10:13 AM
     */
    @RequiresPermissions("article:publish")
    @PostMapping("/listimage")
    public PageInfo listimage(FileConditionVO vo) {
        vo.setPageSize(20);
        return fileService.findImagePageBreakByCondition(vo);
    }

    @RequiresPermissions("files")
    @PostMapping(value = "/remove")
    @BussinessLog("删除文件，ids:{1}")
    public ResponseVO remove(Long[] ids) {
        if (null == ids) {
            return ResultUtil.error(500, "请至少选择一条记录");
        }
        fileService.remove(ids);

        return ResultUtil.success("成功删除 [" + ids.length + "] 张图片");
    }

    @RequiresPermissions("article:publish")
    @PostMapping(value = "/add")
    @BussinessLog("添加文件")
    public ResponseVO add(MultipartFile[] file) {
        if (null == file || file.length == 0) {
            return ResultUtil.error("请至少选择一张图片！");
        }
        int res = fileService.upload(file);
        return ResultUtil.success("成功上传" + res + "张图片");
    }

    @RequiresPermissions("article:publish")
    @GetMapping(value = "/get/{newFileName}")
    @BussinessLog("下载附件，文件名:{1}")
    public void get(@PathVariable("newFileName") String newFileName, HttpServletRequest request, HttpServletResponse response) {
        File file = null;
        if(StringUtils.isNotBlank(newFileName)){
            file = fileService.selectFileByNewFileName(newFileName);
        }
        if(file.getFile()==null){
            return;
        }

//        String contentType = "application/x-msdownload";
        String fileName = file.getOriginalFileName();
        String attachment = "attachment";
        String ext = FilenameUtils.getExtension(newFileName);

        try {
            if (request.getHeader("User-Agent").toLowerCase() .indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes(UTF_8), "ISO8859-1"); // firefox浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, UTF_8);// IE浏览器
            }else if (request.getHeader("User-Agent").toUpperCase().indexOf("EDGE") > 0) {
                fileName = URLEncoder.encode(fileName, UTF_8);// edge
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
                fileName = new String(fileName.getBytes(UTF_8), "ISO8859-1");// 谷歌
            } else {
                fileName = new String(fileName.getBytes("gbk"),"ISO8859_1");
            }
//        response.setContentType(contentType);

            response.addHeader("Content-Disposition",attachment + ";filename=" + fileName);
//        if(contentLength > 0)
//            response.addHeader("Content-Length", contentLength + "");
            OutputStream out = response.getOutputStream();

            FtpApiClient ftpApiClient = SpringContextHolder.getBean(FtpApiClient.class);
            ftpApiClient.download(out,file.getFile().getFullFilePath(),newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /** 
    * @Description: 在页面显示图片
    * @Param: [newFileName, request, response] 
    * @return: void 
    * @Author: wanfy
    * @Date: 2019/3/11 10:09 AM
    */ 
    @RequiresPermissions("article:publish")
    @GetMapping(value = "/showimage/{newFileName}")
    @BussinessLog("下载显示图片，文件名:{1}")
    public void showImage(@PathVariable("newFileName") String newFileName, HttpServletRequest request, HttpServletResponse response) {
        File file = null;
        if(StringUtils.isNotBlank(newFileName)){
            file = fileService.selectFileByNewFileName(newFileName);
        }
        if(file.getFile()==null){
            return;
        }
//        String contentType = "application/x-msdownload";
        String fileName = file.getOriginalFileName();
        String attachment = "inline";

        try {
            if (request.getHeader("User-Agent").toLowerCase() .indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes(UTF_8), "ISO8859-1"); // firefox浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, UTF_8);// IE浏览器
            }else if (request.getHeader("User-Agent").toUpperCase().indexOf("EDGE") > 0) {
                fileName = URLEncoder.encode(fileName, UTF_8);// edge
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
                fileName = new String(fileName.getBytes(UTF_8), "ISO8859-1");// 谷歌
            } else {
                fileName = new String(fileName.getBytes("gbk"),"ISO8859_1");
            }
//        response.setContentType(contentType);

            response.addHeader("Content-Disposition",attachment + ";filename=" + fileName);
//        if(contentLength > 0)
//            response.addHeader("Content-Length", contentLength + "");
            OutputStream out = response.getOutputStream();

            FtpApiClient ftpApiClient = SpringContextHolder.getBean(FtpApiClient.class);
            ftpApiClient.download(out,file.getFile().getFullFilePath(),newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
